<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 商品评论类
 * @package  module
 * @author   allen.qiang
 * @version 1.0
 */

quanli_require('module/base/goods/quanliGoods.class.php');

class goodsComment {

    /**
     * 查询商品评价信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null
     */

    public function searchComments( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //评价id
        if (isset($arg_array['comment_id']) && quanli_is_int($arg_array['comment_id'])) {
            $sql .= ' AND comment_id = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['comment_id'];
        }

        //客户号
        if (isset($arg_array['pcustID']) && quanli_is_int($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //订单号
        if (isset($arg_array['bill_no']) && !empty($arg_array['bill_no'])) {
            $sql .= ' AND bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        //商品名称
        if (isset($arg_array['goodsName']) && !empty($arg_array['goodsName'])) {
            $sql .= ' AND goodsName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['goodsName'];
        }

        //二级商品号
        if (isset($arg_array['twoPostID']) && quanli_is_int($arg_array['twoPostID'])) {
            $sql .= ' AND twoPostID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['twoPostID'];
        }

        //处理状态 0:未回复 1:已回复
        if (isset($arg_array['comment_status']) && ($arg_array['comment_status'] != '') && in_array($arg_array['comment_status'], array(0, 1))) {
            $sql .= ' AND comment_status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['comment_status'];
        }

        //评论来源 0:前台 1:后台
        if (isset($arg_array['comment_from']) && in_array($arg_array['comment_from'], array(0, 1))) {
            $sql .= ' AND comment_from = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['comment_from'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        if (isset($arg_array['rp'])) {

            //统计数量
            $search_sql = 'SELECT COUNT(*) AS item_count FROM content_comments ' . $sql;

            $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            $item_count = $count_array[0]->item_count;
            if ($item_count == 0) {
                $arg_array['count'] = 0;
                return null;
            }

            $arg_array['count'] = $item_count;

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            //分页
            if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                $arg_array['page'] = 1;

            $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

        } else {

            $arg_array['count'] = 0;

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

        }

        //查询信息
        $search_sql = 'SELECT * FROM content_comments ' . $sql;

        $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);

        if (!$temp_item_array)
            return null;

        quanli_include('module/base/customer/quanliCust.class.php');

        //实例会员类
        $quanliCust = new quanliCust();

        //实例商品类
        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

        $item_array = array();

        foreach($temp_item_array as &$item) {

            //查询评价项
            $temp_comments_item_array = $G_SHOP->DBCA->stmt_query('SELECT * FROM content_comments_item WHERE comment_id = ?', 'i', $item->comment_id);

            if (!$temp_comments_item_array) {
                continue;
            }

            $comments_item_array = array();
            foreach($temp_comments_item_array as &$comments_item) {
                $comments_item_array[] = array(
                    'comment_item' => $comments_item->comment_item,
                    'comment_level' => $comments_item->comment_level
                );
            }

            //查询商品信息
            $img_link = ''; $link = ''; $wap_link = ''; $goods_spec = '';
            if( ($item->comment_from) == 0){
                $goods_args_array = array(
                    'postID' => $item->postID
                );
                $goods_array = $quanliGoods->searchGoodsSaleDetail( $goods_args_array );
                if (!$goods_array) {
                    continue;
                }
                $img_link = $goods_array['img_link'];
                $link = $goods_array['link'];
                $wap_link =  $goods_array['wap_link'];
                $goods_spec = $goods_array['spec'];
            }

            $item_array[] = array(
                'creator' => $item->creator,
                'comment_id' => $item->comment_id,
                'postID' => $item->postID,
                'pcustID' => $item->pcustID,
                'goodsName' => $item->goodsName,
                'img_link' => $img_link,
                'link' => $link,
                'wap_link' => $wap_link,
                'goods_spec' => $goods_spec,
                'createTime' => $item->createTime,
                'comment_content' => htmlspecialchars_decode($item->comment_content),
                'ip' => $item->ip,
                'comment_status' => $item->comment_status,
                'answer_content' => $item->answer_content,
                'answer_userID' => $item->answer_userID,
                'answer_dateTime' => $item->answer_dateTime,
                'satisfaction' => $item->satisfaction,
                'display' => $item->display,
                'recommend' => $item->recommend,
                'comment_from' => $item->comment_from,                                      //评价来源
                'comm_item' => $comments_item_array
            );
        }
        return $item_array;
    }

    /**
     * 提交商品评论
     * @param $args_array
     * @return array
     */
    public function saveGoodsComments( $args_array ) {

        global $G_SHOP;

        if (!isset($args_array['bill_no'], $args_array['comments'], $args_array['operator'], $args_array['pcustID'])
            || empty($args_array['bill_no']) || empty($args_array['operator']) || !quanli_is_int($args_array['pcustID']) || empty($args_array['comments'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //加载类文件
        quanli_include('module/base/bill/billSearch.class.php');


        //实例订单类
        $billSearch = new billSearch();

        //实例商品类
        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

        try {

            $G_SHOP->DBCA->beginTransaction();

            //查询订单信息
            $bill_args_array = array(
                'bill_no' => $args_array['bill_no'],
                'pcustID' => $args_array['pcustID']
            );
            $bill_array = $billSearch->searchBillInfo( $bill_args_array );
            if (!$bill_array) {
                throw new Exception('订单信息没有找到', 404);
            }
            if ($bill_array[0]['is_comment'] == 1) {
                throw new Exception('订单已评价', 404);
            }

            //循环订单商品
            foreach($args_array['comments'] as $postID => &$comment) {

                if (!quanli_is_int($postID)) {
                    throw new Exception('订单商品信息错误', 404);
                }

                if (!isset($comment['comment_content']) || empty($comment['comment_content'])) {
                    throw new Exception('请填写评论', 404);
                }
                $comment_content = convertVar($comment['comment_content']);
                if (empty($comment_content)) {
                    throw new Exception('请填写评论', 404);
                }

                if (!isset($comment['comment_item']) || !is_array($comment['comment_item'])) {
                    throw new Exception('请选择评价', 404);
                }

                //查询商品信息
                $goods_args_array = array(
                    'postID' => $postID
                );
                $goods_array = $quanliGoods->searchGoodsSaleDetail( $goods_args_array );

                //保存订单评论信息
                $content_comments_obj = new entity('content_comments');
                $content_comments_obj->creator = $args_array['operator'];
                $content_comments_obj->pcustID = $args_array['pcustID'];
                $content_comments_obj->bill_no = $args_array['bill_no'];
                $content_comments_obj->comment_content = $comment_content;
                $content_comments_obj->postID = $goods_array['postID'];
                $content_comments_obj->goodsName = $goods_array['goodsName'];
                $content_comments_obj->twoPostID = $goods_array['twoPostID'];
                $content_comments_obj->ip = get_ip();
                $G_SHOP->DBCA->save($content_comments_obj);

                $comment_id = $G_SHOP->DBCA->insert_id;

                //保存评论项
                foreach($comment['comment_item'] as &$item) {

                    if (!in_array($item['item_id'], array(1, 2, 3, 4, 5))) {
                        throw new Exception('订单商品评价错误', 404);
                    }
                    if (!in_array($item['level'], array(1, 2, 3, 4, 5))) {
                        throw new Exception('订单商品评价错误', 404);
                    }

                    $content_comments_item_obj = new entity('content_comments_item');
                    $content_comments_item_obj->creator = $args_array['operator'];
                    $content_comments_item_obj->comment_id = $comment_id;
                    $content_comments_item_obj->comment_item = $item['item_id'];
                    $content_comments_item_obj->comment_level = $item['level'];
                    $G_SHOP->DBCA->save($content_comments_item_obj);

                }

            }

            //更新订单为已评价
            $G_SHOP->DBCA->stmt_query('UPDATE bill_master SET is_comment = 1 WHERE bill_no = ?', 's', $args_array['bill_no']);

            $G_SHOP->DBCA->commit();

            return array('code'=> 200, 'message'=> '商品评价提交成功');

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0){
                return array('code'=> $e->getCode(), 'message'=> $e->getMessage());
            }else {
                error_log($e->getMessage());
                return array('code' => 500, 'message'=> '系统错误');
            }

        }

    }

    /*
    * @abstract      editComment()    回复评论
    * @param         $importData = array(必传：'operFlg','answerUserID'
    * 									     可选：'displayFlg'(单条必传),'recommendFlg'(单条必传),'answerInfo'(单条必传),'uuidArr'(批量必传),'uuid'(单条必传))
    * @return        array('code','message')
    *  */
    public function editComment($importData){

        global $G_SHOP;

        quanli_include('module/base/customer/quanliCust.class.php');

        //实例会员类
        $quanliCust = new quanliCust();

        //错误信息
        $error = '';

        $defaultMsg = '感谢您对本公司官网的支持！祝您购物愉快！';//批量回复时默认回复
        $defaultDisFlg = 1;//批量回复时默认全部用户可见
        $defaultRecFlg = 0;//批量回复时默认首页不可见
        /* 传入数据有效性验证start */
        //没有传入数据
        if (empty($importData)) $error .= '没有传入任何数据<br/>';

        if (!isset($importData['operFlg'])){
            $error .= '未传入operFlg<br/>';
        }

        //operFlg：2，单条；3，批量
        if ($importData['operFlg'] != 2 && $importData['operFlg'] != 3) {
            $error .= '传入operFlg错误<br/>';
        }

        if ($importData['operFlg'] == 2 && (!isset($importData['answer_content']) || empty($importData['answer_content']))) {
            $error .= '回复不能为空<br/>';
        }

        if (empty($importData['uuidArr']) && empty($importData['comment_id'])) {
            $error .= '传值错误<br/>';
        }

        if ($importData['operFlg'] == 2 && (!isset($importData['display']))) {
            $error .= '显示控制不能为空<br/>';
        }

        if ($importData['operFlg'] == 2 && (!isset($importData['recommend']) || !is_numeric($importData['recommend']))) {
            $error .= '是否首页显示不能为空<br/>';
        }

        if (!isset($importData['answer_userID']) || empty($importData['answer_userID'])) {
            $error .= '回复人不能为空<br/>';
        }

        if (!empty($error)){
            return array('code' => 400, 'message' => $error);
        }
        /* 传入数据有效性验证end */

        $answerInfo = empty($importData['answer_content']) ? $defaultMsg : $importData['answer_content'];//回复内容
        $uuidArr = empty($importData['comment_id']) ? $importData['uuidArr'] : array($importData['comment_id']);//uuid
        $display = !isset($importData['display']) ? $defaultDisFlg : trim($importData['display']);//显示控制
        $recommendFlg = empty($importData['recommend']) ? $defaultRecFlg : trim($importData['recommend']);//是否首页显示
        $satisfaction = empty($importData['satisfaction']) ? $defaultRecFlg : trim($importData['satisfaction']);//满意度
        $answerUserID = trim($importData['answer_userID']);//回复人

        //保存到数据库
        try {
            if (!empty($uuidArr)){

                foreach ($uuidArr as $uuid) {

                    $old_comment_status = 0;

                    $comment_obj = new entity('content_comments');
                    $comment_obj->comment_id = $uuid;

                    if (!$G_SHOP->DBCA->fetch($comment_obj)){
                        return $return_data = array( 'code' => 400, 'message' => '您的页面已过期，请刷新页面' );
                    }

                    $old_comment_status = $comment_obj->comment_status;
                    $comment_obj->comment_status = 1;
                    $comment_obj->answer_dateTime = date('Y-m-d H:i:s');
                    $comment_obj->answer_content = htmlspecialchars($answerInfo);
                    $comment_obj->display = $display;
                    $comment_obj->recommend = $recommendFlg;
                    $comment_obj->satisfaction = $satisfaction;
                    $comment_obj->answer_userID = $answerUserID;

                    $status = $G_SHOP->DBCA->save($comment_obj,'content');

                    //删除商品评论缓存 add by jackk.zhao 2015-05-28 Start
                    if($status){

                        $redis = $G_SHOP->memoryCache_Instance;

                        $mainResult =  $G_SHOP->DBCA->stmt_query('SELECT twoPostID FROM content_comments WHERE comment_id = ?','i',$uuid);

                        $twoPostID = $mainResult[0]->twoPostID;

                        $redis->remove('goods_comment_'.$twoPostID.'_0');

                        $subResult =  $G_SHOP->DBCA->stmt_query('SELECT comment_item FROM content_comments_item WHERE comment_id = ?','i',$uuid);

                        if($subResult){
                            foreach($subResult as $item){
                                $key = 'goods_comment_'.$twoPostID.'_'.$item->comment_item;
                                $redis->remove($key);
                            }
                        }
                    }
                    //删除商品评论缓存 add by jackk.zhao 2015-05-28 Start

                    //查询会员信息
                    $args_array = array(
                        'pcustID' => $comment_obj->pcustID
                    );

                    $customer_array = $quanliCust->searchCustomerDetail( $args_array );
                    if (!$customer_array) {
                        continue;
                    }

                    if ($old_comment_status == 0) {

                        /**
                         * =============================
                         * 检查会员促销活动
                         * =============================
                         */

                        //加载会员促销类
                        quanli_include('module/base/promotion/promotionCustomer.class.php');


                        //实例会员促销类
                        $promotionHandler = new promotionCustomer();


                        //查询会员促销活动并发放
                        $promotionHandler->grantCustPromotion( $customer_array['pcustID'], $customer_array['custID'], 7 );


                        /**
                         * =============================
                         * 检查会员促销活动
                         * =============================
                         */

                    }

                }


                return $return_data = array( 'code' => 200, 'message' => '回复成功' );
            }

        }catch (Exception $e) {
            error_log($e->getMessage());
            return $return_data = array( 'code' => 500, 'message' => '系统错误' );
        }

    }

    public function deleteComment($importData){

        global $G_SHOP;

        //错误信息
        $error = '';

        /* 传入数据有效性验证start */
        //没有传入数据
        if (empty($importData)) $error .= '没有传入任何数据<br/>';

        if (empty($importData['uuidArr']) || !isset($importData['uuidArr'])) {
            $error .= '传值错误<br/>';
        }

        if (!empty($error)){
            return array('code' => 400, 'message' => $error);
        }
        /* 传入数据有效性验证end */

        $uuidArr = $importData['uuidArr'];//uuid数组

        //操作数据库
        try {
            if (!empty($uuidArr)){
                //循环数组并根据uuid删除评论记录
                foreach ($uuidArr as $uuid){
                    $comment_obj = new entity('content_comments');
                    $comment_obj->comment_id = $uuid;

                    if (!$G_SHOP->DBCA->fetch($comment_obj)){
                        return $return_data = array( 'code' => 400, 'message' => '您的页面已过期，请刷新页面' );
                    }
                    $status = $G_SHOP->DBCA->delete($comment_obj);

                    //删除商品评论缓存 add by jackk.zhao 2015-05-29 Start
                    if($status){

                        $redis = $G_SHOP->memoryCache_Instance;

                        $mainResult =  $G_SHOP->DBCA->stmt_query('SELECT twoPostID FROM content_comments WHERE comment_id = ?','i',$uuid);

                        $twoPostID = $mainResult[0]->twoPostID;

                        $redis->remove('goods_comment_'.$twoPostID.'_0');

                        $subResult =  $G_SHOP->DBCA->stmt_query('SELECT comment_item FROM content_comments_item WHERE comment_id = ?','i',$uuid);

                        if($subResult){
                            foreach($subResult as $item){
                                $key = 'goods_comment_'.$twoPostID.'_'.$item->comment_item;
                                $redis->remove($key);
                            }
                        }
                    }
                    //删除商品评论缓存 add by jackk.zhao 2015-05-29 Start

                }
                return $return_data = array( 'code' => 200, 'message' => '删除成功' );
            }
        }catch (Exception $e){
            error_log($e->getMessage());
            return $return_data = array( 'code' => 500, 'message' => '系统错误' );
        }
    }

}